package cn.xx.quartz.config;

import cn.xx.basic.constant.PayBillConstant;
import cn.xx.order.domain.ProductOrder;
import cn.xx.order.service.IProductOrderService;
import cn.xx.pay.domain.PayBill;
import cn.xx.pay.mapper.PayBillMapper;
import cn.xx.pay.service.IPayBillService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;

public class MainJob implements Job {

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IProductOrderService productOrderService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        Map<String, Object> map = (Map<String, Object>) jobDataMap.get("params");
        String orderSn = (String) map.get("orderSn");


        // 根据订单号查询支付单对象
        PayBill payBill = payBillMapper.findByOrderSn(orderSn);
        // 如果支付单状态为0    就将状态设置为-1 支付失败
        if (payBill.getState() == 0) {
            // 更新支付单状态
            payBill.setState(-1);
            // 设置最后更新时间
            payBill.setUpdateTime(new Date());
        }
        // 更新状态
        payBillMapper.update(payBill);

        // 更新订单状态 判断订单的getBusinessType，分别对应了几种不同的订单
        switch (payBill.getBusinessType()) {
            // 如果订单是product——order类型   因为有五种订单，所以用了常量来区分不同的订单，用key来保存订单id
            case PayBillConstant.PRODUCT_ORDER:
                // 根据支付单BusinessKey(对应类型的订单的id号)查询订单对象
                ProductOrder productOrder = productOrderService.findById(payBill.getBusinessKey());
                // 如果订单状态为0 就将状态设置为-1 支付失败
                if(productOrder.getState() == 0) {
                    // 设置订单状态为-1  支付失败
                    productOrder.setState(-1);
                    // 更新对象
                    productOrderService.update(productOrder);
                }
                break;
            case PayBillConstant.GOODS_ORDER:
                break;
        }
    }
}
